使用套件: react-to-print
安裝套件: npm i react-to-print
功能加上
<--使用componentRef關聯起來>
let componentRef = useRef();
<ReactToPrint
trigger={() => <Button icon={<PrinterOutlined />}>Print</Button>}
content={() => componentRef}
/>
<Table columns={columns} dataSource={dataSource} ref={(el) => (componentRef = el)}/>
<div style={{display:'block',textAlign:'right'}}>
<ReactToPrint
trigger={() => <Button icon={<PrinterOutlined />}>Print</Button>}
content={() => componentRef}
/>
</div>
效果
按右上Print 即可save as PDF
或是 列印
需改進
import './App.css';
import { Table,Button,Layout} from 'antd';
import React, { useState,useRef } from 'react';
import ReactToPrint from "react-to-print";
import { PrinterOutlined } from '@ant-design/icons';
const { Header, Content, Footer } = Layout;
function App() {
const [count, setCount] = useState(0);
const data = [
];
const [dataSource, setDataSource] = useState(data)
let componentRef = useRef();
const handleAdd = () => {
const newData = {
key: count,
no: count+1,
name: ``,
action: <a>Delete</a>,
};
setDataSource([...dataSource, newData]);
setCount(count+1);
};
const handleAdd2 = () => {
const newData1 = {
key: count,
no: count+1,
name: ``,
action: <a>Delete</a>,
};
const newData2 = {
key: count,
no: count+2,
name: ``,
action: <a>Delete</a>,
};
var copiedDataSource = dataSource.slice();
copiedDataSource.push(newData1, newData2);
setDataSource(copiedDataSource);
setCount(count+2);
};
const handleDelete = (key) => {
const newData = dataSource.filter((item) => item.key !== key);
setDataSource(newData);
};
const columns = [
{
title: 'No#',
dataIndex: 'no',
key: 'no'
},
{
title: 'Name',
dataIndex: 'name',
key: 'name'
},
{
title: 'Action',
dataIndex: 'action',
key: 'action',
render: (_, record) =>
dataSource.length >= 1 ? (
<a onClick={() => handleDelete(record.key)}>Delete</a>
) : null,
}
];
return (
<div className="App">
<Layout>
<Header
style={{
color: 'white',
textAlign:'center'
}}
>
桌球出賽名單
</Header>
<Content className="site-layout" style={{ padding: '0 50px' }}
>
<div style={{ padding: 24, height: '100%' }}>
<div style={{display:'block',textAlign:'right'}}>
<ReactToPrint
trigger={() => <Button icon={<PrinterOutlined />}>Print</Button>}
content={() => componentRef}
/>
</div>
<Button type="primary" onClick={handleAdd}>+1 Player</Button>
<Button style={{marginLeft:6}} onClick={handleAdd2}>+2 Player</Button>
<br/><br/>
<Table columns={columns} dataSource={dataSource} ref={(el) => (componentRef = el)}/>
</div>
</Content>
<Footer
style={{
textAlign: 'center',
}}
>
桌球王 ©2023 Created by 阿瑜
</Footer>
</Layout>
</div>
);
}
export default App;